<template>
  <!-- 定位到所在城市 -->
  <div ref="mapContainer" style="width: 100%; height: calc(100vh - 85px)"></div>
</template>

<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";

const mapContainer = ref(null);
// 开发者key
const apiKey = "272fb8f8184785b458a7fc013c9aee43";
let map = null;
let citySearch = null;
let cityName = "";

async function initMap() {
  // 安全密钥
  window._AMapSecurityConfig = {
    securityJsCode: "c1b9edfed89e7fbaa5486856149b9b6f",
  };

  const AMap = await AMapLoader.load({
    key: apiKey,
    version: "2.0",
    plugins: ["AMap.CitySearch"],
  });

  map = new AMap.Map(mapContainer.value, {
    center: [116.397428, 39.90923],
    zoom: 13,
  });

  // //实例化城市查询类
  // citySearch = new AMap.CitySearch();

  // //自动获取用户IP，返回当前城市
  // citySearch.getLocalCity(function(status, result) {
  // 	if (status === 'complete' && result.info === 'OK') {
  // 		let citybounds = result.bounds;
  // 		cityName = result.city;
  // 		//地图显示当前城市
  // 		map.setBounds(citybounds);
  // 		ElMessage.success(`获取城市成功！您当前所在城市：${cityName}`);
  // 	} else {
  // 		ElMessage.success('获取城市失败');
  // 	}
  // });
}

onMounted(async () => {
  await initMap();
});

onUnmounted(() => {
  if (map) {
    map.destroy();
    map = null;
  }
  if (citySearch) {
    citySearch = null;
  }
});
</script>
